import os
import time
import socket as sk
from threading import Thread

server1 = ('free.svipss.top',41477)
server2 = ('free.svipss.top',49412)
server3 = ('free.svipss.top',55539)
server4 = ('free.svipss.top',12343)
threads = 4
progress = 0

def askFor(name,server):
	global threads,progress
	#连接服务器
	s = sk.socket(sk.AF_INET,sk.SOCK_STREAM)
	s.connect(server)
	#发送请求
	s.sendall(bytes(name,'utf-8'))
	#接收size
	percent = int(str(s.recv(1024),'utf-8'))
	#开始接收数据，并写入缓存（Cache）
	with open('Cache/'+name,'wb') as f:
		i = 0
		while True:
			d = s.recv(1024)
			if d:
				f.write(d)
			else:
				break
			if i%percent==0:
				if progress>=100:
					print('\r即将完成，请稍等片刻...',end='')
				else:
					print('\r%f' %progress+'%',end='')
					progress+=1/threads
			i+=1


def merge(*filenames):
	d = bytes()
	for name in filenames:
		with open(name,'rb') as f:
			d+=f.read()
	return d


if __name__ == '__main__':
	os.system('mkdir Cache')
	t1 = Thread(target=askFor,args=('data.7z_1p4',server1))
	t2 = Thread(target=askFor,args=('data.7z_2p4',server2))
	t3 = Thread(target=askFor,args=('data.7z_3p4',server3))
	t4 = Thread(target=askFor,args=('data.7z_4p4',server4))
	t1.start()
	t2.start()
	t3.start()
	t4.start()
	t1.join()
	t2.join()
	t3.join()
	t4.join()
	print('\r正在合并文件，请稍等...        ',end='')
	with open('Cache/data.7z','wb') as f:
		f.write(merge('Cache/data.7z_1p4','Cache/data.7z_2p4','Cache/data.7z_3p4','Cache/data.7z_4p4'))
	print('\r传输完成!                     ')
	progress=0
